package network.impl;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;


import network.NetworkID;
import network.ServerNetworkListener;


class ServerThread implements NetworkID {
	private Socket socket = null;
	private ObjectOutputStream writer = null;
	private ObjectInputStream reader = null;
	
	private Output output;	
	private ServerInputThread input = null;
	
	public ServerThread(Socket socket) {
		this.socket = socket;
		init();
	}
	
	public void addNetworkListener(ServerNetworkListener listener) {
		input.addNetworkListener(listener);
	}
	
	public void addServerInputThreadListener(ServerInputThreadListener listener) {
		input.addInputThreadListener(listener);
	}
	
	public void send(Object obj) {
		output.send(obj);
	}
	
	protected void init() {
		try {	
			OutputStream outputStream = socket.getOutputStream();
	    	InputStream inputStream = socket.getInputStream();
	    	
	    	writer = new ObjectOutputStream(outputStream);
	    	
			reader = new ObjectInputStream(inputStream);
			
			output = new Output(writer);
			
			input = new ServerInputThread(reader, this);
			input.start();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void shutDown() {
		try {
			writer.close();
			reader.close();
			socket.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
